/*
    获取用户信息

    维护用户的收件地址
        增
        删
        改
        查
*/
import * as UserService from '../service/user'
import * as AddressService from '../service/address'
import * as Content from '../constant'


export default {
    namespace: 'user',
    state: {
        user: {
            nickname: '',
            headimgurl: ''
        },
        addressList: {
            list: [],
            map: {}
        }
    },
    reducers: {
        user(state, { payload }) {
            return {
                ...state,
                user: payload
            }
        },
        address(state, { payload }) {
            let list = []
            let map = {}
            if (Array.isArray(payload)) {
                payload.forEach(item => {
                    map[item._id] = item
                    list.push(item)
                    return item
                })
            }
            return {
                ...state,
                addressList: { list, map }
            }
        }
    },
    effects: {
        *login(action, { call, put }) {
            try {
                let res = yield call(UserService.login, action.payload)
                localStorage[Content.TOKEN_KEY] = res['token']
                yield put({ type: 'user', payload: res.data })
                action.resolve()
            } catch (error) {
                action.reject()
            }
        },
        // 曾
        *createAddress({ payload, history }, { call, put, select }) {
            let state = yield select()
            payload.openid = state.user.user.openid
            let res = yield call(AddressService.create, payload)
            history.go(-1)
            yield put({ type: 'findAddress' })
        },
        // 删
        *deleteAddress({ payload, history }, { call, put }){
            let res = yield call(AddressService.del, payload)
            history.go(-1)
            yield put({ type: 'findAddress' })
        },
        // 改
        *updateAddress({ payload, history }, { call, put }){
            let res = yield call(AddressService.update, payload)
            history.go(-1)
            yield put({ type: 'findAddress' })
        },
        // 查
        *findAddress({ }, { call, put, select }) {
            let state = yield select()
            let openid = state.user.user.openid
            let res = yield call(AddressService.find, openid)
            yield put({ type: 'address', payload: res.data })
        }

        // *pay(action, { call }) {
        //     let res = yield call(OrderService.pay, action.payload)
        //     console.log(res)
        //     onBridgeReady(res.data)
        // }
    }
}
